<template>
  <div class="monitoring-container">
    <el-card>
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="12">
            <span>监考记录管理</span>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-button
              type="primary"
              size="small"
              @click="exportExcel"
              :loading="exportLoading">
              <i class="el-icon-download"></i> 导出Excel
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 考试选择卡片 -->
      <el-card shadow="never" class="exam-selector">
        <div slot="header">
          <span>考试筛选</span>
          <el-button
            type="text"
            @click="showExamSelector = !showExamSelector"
            style="float: right; padding: 3px 0">
            {{ showExamSelector ? '收起' : '展开' }}
          </el-button>
        </div>

        <el-collapse-transition>
          <div v-show="showExamSelector">
            <el-form :model="examQuery" :inline="true">
              <el-form-item label="考试类型">
                <el-select
                  v-model="examQuery.type"
                  placeholder="请选择考试类型"
                  clearable
                  style="width: 120px">
                  <el-option label="全部" :value="null" />
                  <el-option label="考试" :value="1" />
                  <el-option label="测评" :value="2" />
                  <el-option label="作业" :value="3" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="loadExamList">查询</el-button>
              </el-form-item>
            </el-form>

            <el-table
              :data="examList"
              border
              highlight-current-row
              @current-change="handleExamSelect"
              style="width: 100%; margin-top: 10px">

              <el-table-column label="考试名称" prop="title" min-width="200" show-overflow-tooltip />
              <el-table-column label="类型" width="80">
                <template slot-scope="scope">
                  <el-tag :type="getExamTypeTag(scope.row.type)">
                    {{ formatExamType(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="getExamStatusTag(scope.row.status)">
                    {{ formatExamStatus(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="开始时间" width="160" prop="startTime" />
              <el-table-column label="结束时间" width="160" prop="endTime" />
            </el-table>

            <pagination
              v-show="examTotal>0"
              :total="examTotal"
              :page.sync="examQuery.pageNum"
              :limit.sync="examQuery.pageSize"
              @pagination="loadExamList" />
          </div>
        </el-collapse-transition>
      </el-card>

      <!-- 考生选择卡片 -->
      <el-card shadow="never" class="student-selector" v-if="currentExam">
        <div slot="header">
          <span>考生筛选 - {{ currentExam.title }}</span>
        </div>

        <el-form :model="studentQuery" :inline="true">
          <el-form-item label="考生姓名">
            <el-input
              v-model="studentQuery.userName"
              placeholder="请输入考生姓名"
              clearable
              style="width: 180px" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="loadStudentList">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="studentList"
          border
          highlight-current-row
          @current-change="handleStudentSelect"
          style="width: 100%; margin-top: 10px">

          <el-table-column label="考生姓名" prop="userName" width="120" />
          <el-table-column label="学号" prop="studentNo" width="120" />
          <el-table-column label="部门" prop="deptName" show-overflow-tooltip />
          <el-table-column label="考试状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getExamStatusTag(scope.row.examStatus)">
                {{ formatExamStatus(scope.row.examStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="成绩" width="100">
            <template slot-scope="scope">
              {{ scope.row.score || '--' }}
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="studentTotal>0"
          :total="studentTotal"
          :page.sync="studentQuery.pageNum"
          :limit.sync="studentQuery.pageSize"
          @pagination="loadStudentList" />
      </el-card>

      <!-- 监考记录搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="事件类型" prop="eventType">
          <el-select
            v-model="queryParams.eventType"
            placeholder="请选择事件类型"
            clearable
            style="width: 120px">
            <el-option label="全部" :value="null" />
            <el-option label="切屏警告" :value="1" />
            <el-option label="强制交卷" :value="2" />
            <el-option label="异常行为" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="处理状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择处理状态"
            clearable
            style="width: 120px">
            <el-option label="全部" :value="null" />
            <el-option label="未处理" :value="0" />
            <el-option label="已处理" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 380px">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 监考记录表格 -->
      <el-table
        :data="logList"
        border
        v-loading="loading"
        @sort-change="handleSortChange"
        style="width: 100%">

        <el-table-column label="ID" prop="id" width="80" sortable="custom" />

        <el-table-column label="考试名称" prop="examTitle" width="180" show-overflow-tooltip />

        <el-table-column label="场次" prop="sessionName" width="150" />

        <el-table-column label="考生" prop="userName" width="120" />

        <el-table-column label="事件类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getEventTypeTag(scope.row.eventType)">
              {{ formatEventType(scope.row.eventType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="事件时间" prop="eventTime" width="160" sortable="custom">
          <template slot-scope="scope">
            {{ parseTime(scope.row.eventTime) }}
          </template>
        </el-table-column>

        <el-table-column label="截图" width="100">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.screenshot"
              style="width: 80px; height: 45px"
              :src="scope.row.screenshot"
              :preview-src-list="[scope.row.screenshot]"
              fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-else>无</span>
          </template>
        </el-table-column>

        <el-table-column label="处理状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.handleBy ? 'success' : 'warning'">
              {{ scope.row.handleBy ? '已处理' : '未处理' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleDetail(scope.row)">
              详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              v-if="!scope.row.handleBy"
              @click="handleProcess(scope.row)">
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      title="监考记录详情"
      :visible.sync="detailDialogVisible"
      width="700px"
      :close-on-click-modal="false">

      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="考试名称">{{ currentLog.examTitle }}</el-descriptions-item>
        <el-descriptions-item label="场次">{{ currentLog.sessionName }}</el-descriptions-item>
        <el-descriptions-item label="考生">{{ currentLog.userName }}</el-descriptions-item>
        <el-descriptions-item label="事件类型">
          {{ formatEventType(currentLog.eventType) }}
        </el-descriptions-item>
        <el-descriptions-item label="事件时间">{{ parseTime(currentLog.eventTime) }}</el-descriptions-item>
        <el-descriptions-item label="设备信息" :span="2">
          {{ currentLog.deviceInfo || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ipAddress || '无' }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="currentLog.handleBy ? 'success' : 'warning'">
            {{ currentLog.handleBy ? '已处理' : '未处理' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人" v-if="currentLog.handleBy">
          {{ currentLog.handleByName }}
        </el-descriptions-item>
        <el-descriptions-item label="处理时间" v-if="currentLog.handleBy">
          {{ parseTime(currentLog.updateTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="处理结果" :span="2" v-if="currentLog.handleBy">
          {{ currentLog.handleResult || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="事件详情" :span="2">
          {{ currentLog.eventDetails || '无' }}
        </el-descriptions-item>
      </el-descriptions>

      <div class="screenshot-container" v-if="currentLog.screenshot">
        <h4>截图证据：</h4>
        <el-image
          :src="currentLog.screenshot"
          fit="contain"
          style="max-width: 100%; max-height: 400px;">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 处理对话框 -->
    <el-dialog
      title="处理监考事件"
      :visible.sync="processDialogVisible"
      width="500px"
      :close-on-click-modal="false">

      <el-form
        :model="processForm"
        ref="processForm"
        label-width="80px"
        :rules="processRules">

        <el-form-item label="处理结果" prop="result">
          <el-input
            type="textarea"
            :rows="4"
            v-model="processForm.result"
            placeholder="请输入处理结果（如：警告考生、取消成绩等）"
            maxlength="500"
            show-word-limit />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getMonitoringLogs, handleMonitoringEvent} from '@/api/exam/monitoring'
import {getExamActivities, getStuListOfActivity } from '@/api/exam/examActivity'
import {parseTime} from '@/utils/quiz'

export default {
  name: 'MonitoringTab',
  props: {
    groupId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      // 加载状态
      loading: false,
      exportLoading: false,

      // 考试筛选相关
      showExamSelector: true,
      examQuery: {
        pageNum: 1,
        pageSize: 10,
        type: null
      },
      examList: [],
      examTotal: 0,
      currentExam: null,

      // 考生筛选相关
      studentQuery: {
        pageNum: 1,
        pageSize: 10,
        userName: ''
      },
      studentList: [],
      studentTotal: 0,
      currentStudent: null,

      // 监考记录查询
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: this.groupId,
        examId: null,
        userId: null,
        eventType: null,
        status: null,
        timeRange: []
      },

      // 数据列表
      logList: [],
      total: 0,

      // 详情对话框
      detailDialogVisible: false,
      currentLog: {},

      // 处理对话框
      processDialogVisible: false,
      processForm: {
        logId: null,
        result: ''
      },
      processRules: {
        result: [
          {required: true, message: '请输入处理结果', trigger: 'blur'},
          {min: 5, message: '处理结果至少5个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.loadExamList()
  },
  methods: {
    // 加载考试列表
    loadExamList() {
      getExamActivities({
        groupId: this.groupId,
        type: this.examQuery.type,
        pageNum: this.examQuery.pageNum,
        pageSize: this.examQuery.pageSize
      }).then(response => {
        this.examList = response.rows
        this.examTotal = response.total
      })
    },

    // 选择考试
    handleExamSelect(exam) {
      this.currentExam = exam
      this.queryParams.examId = exam ? exam.id : null
      this.loadStudentList()
      this.getList()
    },

    // 加载考生列表
    loadStudentList() {
      if (!this.currentExam) return

      getStuListOfActivity({
        examId: this.currentExam.id,
        groupId: this.groupId,
        userName: this.studentQuery.userName,
        pageNum: this.studentQuery.pageNum,
        pageSize: this.studentQuery.pageSize
      }).then(response => {
        this.studentList = response.rows
        this.studentTotal = response.total
      })
    },

    // 选择考生
    handleStudentSelect(student) {
      this.currentStudent = student
      this.queryParams.userId = student ? student.userId : null
      this.getList()
    },

    // 加载监考记录
    getList() {
      this.loading = true

      const params = {
        ...this.queryParams,
        startTime: this.queryParams.timeRange && this.queryParams.timeRange[0],
        endTime: this.queryParams.timeRange && this.queryParams.timeRange[1]
      }

      getMonitoringLogs(params).then(response => {
        this.logList = response.rows
        this.total = response.total
      }).finally(() => {
        this.loading = false
      })
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.timeRange = []
      this.handleQuery()
    },

    // 排序
    handleSortChange({column, prop, order}) {
      // 这里可以添加排序逻辑
      this.$message.info(`按 ${prop} ${order === 'ascending' ? '升序' : '降序'} 排序`)
      this.getList()
    },

    // 格式化考试类型
    formatExamType(type) {
      const typeMap = {
        1: '考试',
        2: '测评',
        3: '作业'
      }
      return typeMap[type] || '未知'
    },

    // 获取考试类型标签样式
    getExamTypeTag(type) {
      const tagMap = {
        1: 'primary',
        2: 'success',
        3: 'info'
      }
      return tagMap[type] || ''
    },

    // 格式化考试状态
    formatExamStatus(status) {
      const statusMap = {
        0: '未开始',
        1: '进行中',
        2: '已结束',
        3: '已归档'
      }
      return statusMap[status] || '未知'
    },

    // 获取考试状态标签样式
    getExamStatusTag(status) {
      const tagMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: ''
      }
      return tagMap[status] || ''
    },

    // 格式化事件类型
    formatEventType(type) {
      const typeMap = {
        1: '切屏警告',
        2: '强制交卷',
        3: '异常行为'
      }
      return typeMap[type] || '未知'
    },

    // 获取事件类型标签样式
    getEventTypeTag(type) {
      const tagMap = {
        1: 'warning',
        2: 'danger',
        3: 'info'
      }
      return tagMap[type] || ''
    },

    // 查看详情
    handleDetail(row) {
      this.currentLog = row
      this.detailDialogVisible = true
    },

    // 处理记录
    handleProcess(row) {
      this.processForm.logId = row.id
      this.processForm.result = ''
      this.processDialogVisible = true
      this.$nextTick(() => {
        this.$refs.processForm.clearValidate()
      })
    },

    // 提交处理
    submitProcess() {
      this.$refs.processForm.validate(valid => {
        if (valid) {
          handleMonitoringEvent(this.processForm.logId, this.processForm.result)
            .then(() => {
              this.$message.success('处理成功')
              this.processDialogVisible = false
              this.getList()
            })
        }
      })
    },

    // 导出Excel
    exportExcel() {
      this.exportLoading = true
      // 这里添加导出逻辑
      setTimeout(() => {
        this.$message.success('导出成功')
        this.exportLoading = false
      }, 1500)
    },

    // 时间格式化
    parseTime(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
    }
  }
}
</script>

<style scoped>
.monitoring-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.exam-selector, .student-selector {
  margin-bottom: 20px;
}

.screenshot-container {
  margin-top: 20px;
  text-align: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.text-right {
  text-align: right;
}
</style>
